package cz.muni.fi.pa165.dundd.web;

import cz.muni.fi.pa165.dundd.dto.HeroDTO;
import cz.muni.fi.pa165.dundd.service.HeroService;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrorHandler;
import net.sourceforge.stripes.validation.ValidationErrors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;

/**
 *
 * @author xdemocko
 */
public class RegActionBean extends BaseActionBean implements ValidationErrorHandler {

    final static Logger log = LoggerFactory.getLogger(RegActionBean.class);
    @SpringBean
    HeroService heroService;
    @ValidateNestedProperties(value = {
        @Validate(on = {"add"}, field = "name", required = true),
        @Validate(on = {"add"}, field = "password", required = true)
    })
    private HeroDTO hero;

    public HeroDTO getHero() {
        return hero;
    }

    public void setHero(HeroDTO hero) {
        this.hero = hero;
    }

    public Resolution add() {
        String notHashedPass = hero.getPassword();
        ShaPasswordEncoder encoder = new ShaPasswordEncoder();
        String hashedPass = encoder.encodePassword(notHashedPass, hero.getName());
        hero.setPassword(hashedPass);
        heroService.createHero(hero);
        getContext().getMessages().add(new LocalizableMessage("reg.add.message", escapeHTML(hero.getName())));
        return new ForwardResolution("login.jsp");
    }

    @Override
    public Resolution handleValidationErrors(ValidationErrors errors) throws Exception {
        return null;
    }

}
